package com.xuecheng.system.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LoginDto;
import com.xuecheng.commons.model.vo.LoginVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.JwtUtils;
import com.xuecheng.system.domain.User;
import com.xuecheng.web.exception.BusinessException;
import com.xuecheng.system.mappers.UserMapper;
import com.xuecheng.system.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Sober_wxy
 * @date 2022/7/15 17:12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
        /**
         * 用户登录
         * @param loginDto -- user
         * @return
         */
        @Override
        public ResponseResult login(LoginDto loginDto) {
                // 获取用户登录信息
                String phone = loginDto.getUsername();
                String password = loginDto.getPassword();
                String utype = loginDto.getUtype();
                if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(password) || StringUtils.isEmpty(utype)) {
                        throw new BusinessException(ErrorCode.PARAMSERROR);
                }
                // 拿到参数 查询用户 通过 phone + utype 指定
                LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(User::getPhone,phone);
                queryWrapper.eq(User::getUtype,utype);
                User user = this.getOne(queryWrapper);
                // 判断是否存在该用户
                if(user == null){
                        throw new BusinessException(ErrorCode.LOGINERROR);
                }
                // 判断密码
                password = DigestUtil.md5Hex(password);
                if (!password.equals(user.getPassword())) {
                        throw new BusinessException(ErrorCode.LOGINERROR);
                }
                // 登录成功后 map集合存储用户登录数据
                Map map = new HashMap();
                map.put("userId",user.getId());
                map.put("companyId",user.getCompanyId());
                map.put("companyName",user.getCompanyName());
                //通过JWT 创建token 传入map 超时时间
                String token = JwtUtils.createToken(map, 360);
                // 返回数据vo
                LoginVo loginVo = new LoginVo();
                loginVo.setAccess_token(token);
                loginVo.setUsername(user.getName());
                return ResponseResult.okResult(loginVo);
        }
}
